package com.beforedawn.compile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class Compile {
    CompileCommand compileCommand;

    public Compile(CompileCommand compileCommand) {
        this.compileCommand = compileCommand;
    }

    public CompileState handle(String filepath) {
        Process process;
        int exitValue;
        try {
            process = Runtime.getRuntime().exec(compileCommand.getCompileCommand().replaceAll("filename", filepath));
            BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = error.readLine()) != null) {
                System.out.println(line);
            }
            exitValue = process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return CompileState.SE;
        }

        if (exitValue == 0) {
            return CompileState.SUCCESS;
        }
        return CompileState.FAIL;
    }
}
